<?php
namespace App\Http\Controllers\Api\V6;
use App\Common\ApiData;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use App\Models\V1\MemberModel;

class PayController extends Controller{

    private $isSandbox = false;

    public function log_ios_pay(){
        $apiData    = new ApiData();
        $apiData->message   = "ok";
        $apiData->code      = 200;
        return $apiData->send();
    }



    /**
     * 下单
     * @param $request Request 请求的书籍
     * @return object
     * */
    public function add_order(Request $request){
        $apiData        = new ApiData();
        $orderNumber    = create_order_number();
        $isoData        = "";
        $payMoney       = 3000;
        $payType        = $request->input('payType');
        $goodsId        = "com.xiaonangua.jiaodaodushuhui001";
        $mobile         = $request->input('mobile','');
        $key            = $request->input('key');

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        if($memberInfo == false){
            $memberInfo = new \stdClass();
            $memberInfo->MemNumber = '';
        }
        $data = [
            'app_key'       => $key,
            'OrderNumber'   => $orderNumber,
            'MemNumber'     => $memberInfo->MemNumber,
            'ios_receipt_data' => $isoData,
            'pay_money'     => $payMoney,
            'pay_type'      => $payType,
            'goods_id'      => $goodsId,
            'pay_status'    => 0,
            'AddDate'       => date_time()
        ];




        DB::table('orderprepaidlog')->insert($data);
        $apiData->message   = "ok";
        $apiData->code      = 200;
        $apiData->set_data('orderNumber',$orderNumber);
        return $apiData->send();
    }


    /**
     * 检查ios内购支付的结果
     * @param $request Request
     * */
    public function check_ios_pay_result(Request $request){

        $apiData    = new ApiData();

        //获取 App 发送过来的数据,设置时候是沙盒状态
        $receipt        = $request->input('receiptData');
        $orderNumber    = $request->input('orderNumber');
        $key            = $request->input('key');
        $mobile         = $request->input('mobile');
        $isSandbox      = $this->isSandbox;
        $memberModel    = new MemberModel();

        //1.检查用户是否存在
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);

        //2.检查本订单是否已经过验证
        $orderModel = DB::table('orderprepaidlog')->where('OrderNumber',$orderNumber);
        $orderInfo  = $orderModel->first();
        if(!$orderInfo){
            $apiData->message   = "订单不存在";
            $apiData->code      = 3002;
            return $apiData->send();
        }

        if($orderInfo->pay_status == 1){
            $apiData->message   = "订单支付成功";
            $apiData->code      = 200;
            return $apiData->send();
        }

        //保存验证凭证
        $newOrderData   = [];
        if(empty($orderInfo->ios_receipt))
        {
            $newOrderData['ios_receipt'] = json_encode($request->all());
        }

        //开始执行验证
        try
        {
            //完善支付信息
            $info = $this->getReceiptData($receipt, $isSandbox);
            $newOrderData['pay_status']         = $info['status'];
            $newOrderData['pay_result_info']    = $info['data'];
            $orderModel->update($newOrderData);

            // 通过product_id 来判断是下载哪个资源
            if($info['status'] == 1){ //成功

                //修改会员的有效时间
                if($memberInfo != false){
                    $surplusTime    = strtotime($memberInfo->MemEndTime)-time();
                    $year   = date('Y',time());
                    $month  = date('m',time());
                    $date   = date('d',time());
                    $endTime    = ($year+1)."-".$month."-".$date." 00:00:00";

                    if($surplusTime > 0){
                        $endTime    = strtotime($endTime) + $surplusTime;
                        $endTime    = date('Y-m-d H:i:s',$endTime);
                    }
                    $memberData     = ['MemEndTime'=>$endTime,'States'=>1,'UserID'=>$memberInfo->UserID];
                    $memberModel->update_member_info($memberData);
                }
                $apiData->message   = "ok";
                $apiData->code      = 200;
                return $apiData->send();
            }else{  //失败

                $apiData->message   = "验证失败".$info['msg'];
                $apiData->code      = 201;
                return $apiData->send();
            }
        }

        //捕获异常
        catch(Exception $e)
        {
            $apiData->message   = $e->getMessage();
            $apiData->code      = 400;
            return $apiData->send();
        }
    }







    public function getReceiptData($receipt,$isSandbox = false){


        if ($isSandbox) {
            $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';
        }
        else {
            $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';
        }
        
        $postData = json_encode(
            array('receipt-data' => $receipt)
        );

        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加，不加会报SSL 错误
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);


        $response = curl_exec($ch);
        $errno    = curl_errno($ch);
        $errmsg   = curl_error($ch);
        curl_close($ch);

        

        //判断时候出错，抛出异常
        if ($errno != 0) {
            $msg    = $errno.":".$errmsg;
            $result =  ['status' => 0, 'msg' => $msg,'data'=>''];
            return $result;
        }

        $data = json_decode($response);

        //判断返回的数据是否是对象
        if (!is_object($data))
        {
            $msg    = "return data :".$response;
            return ['status' => 0, 'msg' => $msg,'data'=>$response];
        }


        //判断购买时候成功
        if (!isset($data->status) || $data->status != 0)
        {
            $msg = "buy faile,return data :".$response;
            return ['status'=>0,'msg'=>$msg,'data'=>$response];
        }


        //返回产品的信息
        //$payResult   = $data->receipt->in_app;
        //$payResult   = $payResult[0];

        //验证支付失败
        if($data->status != 0)
        {
            $msg    = "buy faile,return data :".$response;
            return ['status'=>0,'msg'=>$msg,'data'=>$response];
        }

        //支付成功
        return ['status'=>1,'msg'=>'支付成功','data'=>$response];

        /*
        return array(
            'quantity'       =>  $data1->quantity,
            'product_id'     =>  $data1->product_id,
            'transaction_id' =>  $data1->transaction_id,
            'purchase_date'  =>  $data1->purchase_date,
            'app_item_id'    =>  $data1->app_item_id,
            'bid'            =>  $data1->bid,
            'bvrs'           =>  $data1->bvrs
        );*/
    }
}